﻿namespace Huayou.Utils
{
    using System;
    using System.Security.Cryptography;
    using System.Text;
    using System.Web.Security;

    public class Cipher
    {
        private static byte[] b_iv = new byte[8];
        private static byte[] b_key = new byte[8];
        private static string s_iv = "        ";
        private static string s_key = "        ";

        public static byte[] DecryptDES(byte[] b)
        {
            return Encrypt(b, false);
        }

        public static string DecryptDES(string text)
        {
            byte[] bytes = DecryptDES(Encoding.Unicode.GetBytes(text));
            return Encoding.Unicode.GetString(bytes);
        }

        private static byte[] Encrypt(byte[] b, bool bl_crypt)
        {
            byte[] buffer;
            DES des = DES.Create();
            des.IV = b_iv;
            des.Key = b_key;
            if (bl_crypt)
            {
                buffer = des.CreateEncryptor().TransformFinalBlock(b, 0, b.Length);
            }
            else
            {
                buffer = des.CreateDecryptor().TransformFinalBlock(b, 0, b.Length);
            }
            des.Clear();
            return buffer;
        }

        public static byte[] EncryptDES(byte[] b)
        {
            return Encrypt(b, true);
        }

        public static string EncryptDES(string text)
        {
            byte[] bytes = EncryptDES(Encoding.Unicode.GetBytes(text));
            return Encoding.Unicode.GetString(bytes);
        }

        public static string EncryptMD5(string text)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(text, "MD5");
        }

        public static byte[] EncryptTripleDES(byte[] b, bool bl_crypt)
        {
            return null;
        }

        public static string IV
        {
            get
            {
                return s_iv;
            }
            set
            {
                s_iv = value + "         ";
                char[] destination = new char[8];
                s_iv.CopyTo(0, destination, 0, 8);
                b_iv = Encoding.Unicode.GetBytes(destination);
            }
        }

        public static string Key
        {
            get
            {
                return s_key;
            }
            set
            {
                s_key = value + "         ";
                char[] destination = new char[8];
                s_key.CopyTo(0, destination, 0, 8);
                b_key = Encoding.Unicode.GetBytes(destination);
            }
        }
    }
}

